package main

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/tx7do/kratos-transport/broker"
	"github.com/tx7do/kratos-transport/broker/nsq"
	"kratos_kafka/internal/utils"
	"kratos_kafka/internal/utils/mq_nsq"
	"time"
)

func main() {

	ctx := context.Background()
	brokerNsq := nsq.NewBroker(
		broker.WithOptionContext(ctx),
		broker.WithAddress([]string{"127.0.0.1:4150"}...),
	)
	errInit := brokerNsq.Init()
	if errInit != nil {
		panic(errInit)
	}
	if err := brokerNsq.Connect(); err != nil {
		panic(err)
	}

	// nameLst := []string{"whw1", "whw2", "whw3", "whw4", "whw5", "whw6", "whw7", "whw8", "whw9"}
	nameLst := []string{"whw1", "whw2"}

	// go get github.com/nsqio/go-nsq@v1.1.0
	//donChan := make(chan *goNsq.ProducerTransaction, 1)

	for idx, name := range nameLst {
		// 每隔1s发一次消息
		time.Sleep(time.Second)

		currEvent := mq_nsq.BookData{
			Title:       name,
			Desc:        "desc...",
			Authors:     []string{name},
			PublishTime: time.Now(),
		}
		body, errBody := json.Marshal(currEvent)
		if errBody != nil {
			fmt.Println("errBody: ", errBody)
			return
		}

		errPublish := brokerNsq.Publish(
			"book_topic_local",
			body,
			// TODO 异步发送消息: 实际上不太靠谱(尽量别用) tests/kratos_nsq中测试显示 donChan长度大于1或者测试代码中for循环有time.Sleep时会有消息丢失！
			// TODO 有时间研究下 asyncPublishKey这个key 对应的使用方法 PublishAsync/DeferredPublishAsync
			//nsq.WithAsyncPublish(donChan),

			// Notice 延迟消息
			// Notice deferredPublishKey这个key 对应的使用方法 DeferredPublishAsync/DeferredPublish —— 实际用了"DPUB"命令 应该是NSQ自带的
			nsq.WithDeferredPublish(time.Second*3),
		)

		if errPublish != nil {
			fmt.Println("err: ", idx, errPublish)
		} else {
			fmt.Printf("%v 发送了数据: %v \n", utils.GetCurrentTime(), string(body))
		}
	}

}
